import 'package:json_annotation/json_annotation.dart';
import '../utils/timestamp_utils.dart'; // 导入工具类
part 'comment_model.g.dart';

@JsonSerializable()
class Comment {
  @JsonKey(name: 'postId')
  final int postId;

  @JsonKey(name: 'id')
  final int id;

  @JsonKey(name: 'name')
  final String name;

  @JsonKey(name: 'email')
  final String email;

  @JsonKey(name: 'body')
  final String body;

  // 添加额外字段
  @JsonKey(name: 'createdAt', fromJson:TimestampUtils.fromJson, toJson: TimestampUtils.toJson)
  final DateTime? createdAt;

  @JsonKey(name: 'userId')
  final int? userId;

  @JsonKey(name: 'avatarUrl')
  final String? avatarUrl;

  @JsonKey(name: 'likeCount', defaultValue: 0)
  final int likeCount;


  Comment({
    required this.postId,
    required this.id,
    required this.name,
    required this.email,
    required this.body,
    this.createdAt,
    this.userId,
    this.avatarUrl,
    this.likeCount = 0,
  });
  // 匿名邮箱
  String get anonymizedEmail {
    if (email.isEmpty) return '';
    final parts = email.split('@');
    if (parts.length != 2) return email;
    final username = parts[0];
    final domain = parts[1];

    if (username.length <= 2) {
      return '***@$domain';
    }

    return '${username.substring(0, 1)}***${username.substring(username.length - 1)}@$domain';
  }
  // 格式化创建时间
  String get formattedCreatedAt => TimestampUtils.format(createdAt);

  // 相对时间
  String get relativeTime => TimestampUtils.relativeTime(createdAt);
  factory Comment.fromJson(Map<String,dynamic> json) =>_$CommentFromJson(json);
  Map<String,dynamic> toJson() => _$CommentToJson(this);


  // 获取显示名称
  String get displayName {
    if (name.isNotEmpty) return name;
    return email.split('@').first;
  }
}
